package org.zjt.classloader;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.lang.reflect.Field;

/**
 * Description:
 *
 *          利用groovy class loader 实现类的动态加载。用于一些动态策略。
 *
 * @author juntao.zhang
 * Date: 2018-07-12 上午10:24
 * @see
 */
@Slf4j
public class GroovyClassLoaderTest {



    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, InstantiationException {

        String classText = "class BeanAccessor {  \n" +
                "    def dftField(){" +
                "       return \"zhangsan\";" +
                "    }  \n" +
                "    private priField;  \n" +
                "    protected protField;  \n" +
                "     \n" +
                "}  ";


        GroovyClassLoader cLoader = new GroovyClassLoader(GroovyClassLoaderTest.class.getClassLoader());

        Class aClass = cLoader.parseClass(classText);

        GroovyObject groovyObject = (GroovyObject)aClass.newInstance();

        groovyObject.setProperty("protField","sdsssssss");
        Object protField1 = groovyObject.getProperty("protField");
        log.info(String.valueOf(protField1));

        Object dftField = groovyObject.invokeMethod("dftField", new Object[0]);

        log.info(String.valueOf(dftField));
    }


}
